#include <string>
#include <iostream>
#include <mysql/mysql.h>
#include <cstdlib>
#include <stdio.h>
#include <cstdio>
#include <stdlib.h>
#include <sys/stat.h>
#include <vector>

#include "query.h"
#include "logint.h"
#include "util.h"
#include "DBconfigurations"

using namespace std;

Query::Query()
{
ReturnElementsCount=-1;
}

Query::Query(string Query_String)
{
QueryString=Query_String;
ReturnElementsCount=-1;
}

Query::~Query()
{
}

bool Query::Execute()
{
///Connect to DB
MYSQL *connection,mysql;
mysql_init(&mysql);
connection=mysql_real_connect(&mysql,HOST,USER,PASSWORD,DBNAME,0,0,0);
if(connection==NULL)
      {
        string ErrorMsg="MYSQL ERROR: ";
	ErrorMsg+=mysql_error(&mysql);
	LogInt LogErrorMsg('E',ErrorMsg,"");
	LogErrorMsg.Display();
        return false;
        }
///Connection Successfull

const char *query_char=QueryString.c_str();
MYSQL_RES *result;
MYSQL_ROW row;

int query_state;
string query_results;

query_state=mysql_query(connection,query_char);

//Query couldn't be executed
if(query_state!=0)
        {
        string the_error="query not succesfful: ";
	the_error+=mysql_error(connection);
	LogInt p_error('E',the_error,"");
	p_error.Display();
	return false;
        }

///Query executed
result=mysql_store_result(connection);

///Fetch data
if(result!=0)
        {
        while((row=mysql_fetch_row(result))!=NULL)
                {
		if(row[0]!=0){
                ReturnElements.push_back(row[0]);
		ReturnElementsCount++;
		LastElementReturned=row[0];	
		}
                }
        }
mysql_free_result(result);

//Disconnect from DB
mysql_close(connection);

return true;
}

int Query::GetReturnElementsCount()
{
	return ReturnElementsCount;
}

vector<string> Query::GetReturnElements()
{
	return ReturnElements;
}

string Query::GetLastElementReturned()
{
	return LastElementReturned;
}

string Query::GetReturnElementAtPosition(int ElementPosition)
{
	return ReturnElements.at(ElementPosition); 
}

string Query::GetReturnElementsNumbered()
{
///Get elements in a numbered way
int cnt=-1;
string disp="";
while(cnt++<ReturnElementsCount)
	{
	disp+=ConvertIntToString(cnt);
	disp+=") ";
	disp+=ReturnElements.at(cnt);
	disp+="\n";
	}

return disp;
}

void Query::SetQueryString(string String)
{
	QueryString=String;
}

string Query::GetReturnElementsUnnumbered()
{
///get elements in an unnumbered way
int cnt=-1;
string disp="";
while(cnt++<ReturnElementsCount)
        {
        disp+=ReturnElements.at(cnt);
        disp+="\n";
        }
return disp;
}
